<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>鼠标绘制不同颜色的点</title>
  </head>
  <body>
    <canvas id="glcanvas" width="800" height="600"> your browser don't support canvas </canvas>
    <p>鼠标点击绘制</p>

    <script src="../lib/webgl-utils.js"></script>
    <script src="../lib/webgl-debug.js"></script>
    <script src="../lib/cuon-utils.js"></script>

    <script>
        var VSHADER_SOURCE = `
              attribute vec4 a_Position;
              void main(){
                  gl_Position = a_Position;
                  gl_PointSize = 10.0;
              }
          `;
  
        var FSHADER_SOURCE = `
              precision mediump float;
              uniform vec4 u_FragColor;
              void main(){
                  gl_FragColor = u_FragColor;
              }
          `;
  
        var canvas = document.getElementById("glcanvas");
  
        var gl = getWebGLContext(canvas);
        if (!gl) throw new Error("can't get canvas context");
  
        if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE))
          throw new Error("can't init shaders");
  
        var a_Position = gl.getAttribLocation(gl.program, "a_Position");
        var u_FragColor = gl.getUniformLocation(gl.program, "u_FragColor");

        if (a_Position < 0)
          throw new Error("can't get storage location of a_Position");
        if(u_FragColor < 0)
          throw new Error("can't get storage location of u_FragColor");
  
        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.clear(gl.COLOR_BUFFER_BIT);
  
        let points = [];
        let colors = [];
        document.body.addEventListener("click", (e) => {
          let canvas = e.target;
          let rect = e.target.getBoundingClientRect();
          let x = e.clientX - rect.left;
          let y = e.clientY - rect.top;
  
          x = (x - canvas.width / 2) / canvas.width * 2;
          y = (canvas.height / 2 - y) / canvas.height * 2;
          points.push([x, y]);
          colors.push([Math.random(), Math.random(), Math.random(), 1.0]);

          gl.clearColor(0.0, 0.0, 0.0, 1.0);
          gl.clear(gl.COLOR_BUFFER_BIT);
          for (let i = 0; i < points.length; i++) {
            gl.vertexAttrib3f(a_Position, points[i][0], points[i][1], 0.0);
            gl.uniform4f(u_FragColor, colors[i][0], colors[i][1], colors[i][2], colors[i][3]);
            gl.drawArrays(gl.POINTS, 0, 1);
          }
        });
      </script>
  </body>
</html>
